package com.xhg.model;

import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.xhg.common.PageNavation;

/**
 *  y_power model.
 *	将表结构放在此，消除记忆负担
 *	mysql> desc y_user;
 *	-----------------------------------------------------------------------------------
 *	字段名			Id		userName	password	identity	state	createTime
 *	Comment		id		用户名			密码 			标记位			状态		创建时间
 *	类型			bigint	varchar		varchar     int			int		timestamp
 *	Null		NO		NO			NO			NO			NO		NO
 *	默认值											1			1		CURRENT_TIMESTAMP
 *	-----------------------------------------------------------------------------------
 *	数据库字段名建议使用驼峰命名规则，便于与 java 代码保持一致，如字段名： userId
 */
public class Power extends Model<Power> implements BaseModelImpl<Power,Long>{
	
	private static final long serialVersionUID = -2065543982276604060L;

	private static String sql;
	
	public static final Power dao = new Power();

	@Override
	public boolean save(Power obj) {
		return obj.save();
	}
	@Override
	public boolean update(Power obj) {
		return obj.update();
	}
	@Override
	public Power queryById(Long id) {
		sql="SELECT p.*,p2.powerName AS fatherName FROM y_power p "
		+"LEFT JOIN y_power p2 ON ( p2.id=p.fatherId AND p2.state=1) WHERE p.state=1 AND p.id="+id;
		Power power=dao.findFirst(sql);
		return power;
	}
	@Override
	public boolean deleteByIds(String ids) {
		String sql = "update y_power SET state=0 WHERE id in("+ids+")";
		return Db.update(sql)>0;
	}
	@Override
	public Page<Power> queryList(PageNavation page) {
		sql="FROM y_power p LEFT JOIN y_power p2 ON (p2.id=p.fatherId AND p2.state=1) WHERE p.state=1 ";
		if(page.getSearch()!=null){sql+="AND p.powerName LIKE '%"+page.getSearch()+"%' " ;}
		if(page.getSort()!=null){
			sql+="ORDER BY p."+page.getSort()+" ";
		}else{
			sql+="ORDER BY p.id ";
		}
		if(page.getOrder()!=null){
			sql+=page.getOrder();
		}else{
			sql+="desc";
		}
		Page<Power> powerPage=dao.paginate(page.getPageNumber(),page.getPageSize(),
				"SELECT p.*,p2.powerName AS fatherName ",sql);
		return powerPage;
	}
	/**
	 * zTree异步加载数数据
	 */
	public List<Power> queryListByFid(Long fatherId) {
		sql="SELECT *,'true' as isParent FROM y_power WHERE state=1 AND type='M' AND fatherId=? order by id ASC";
		List<Power> pList=dao.find(sql,fatherId);
		return pList;
	}
    /**
     * 验证权限代码是否已存在
     */
    public Boolean isExistPowerCode(Map<String,Object> paramMap) {
    	sql="SELECT COUNT(id) FROM y_power WHERE state=1 AND powerCode='"+paramMap.get("power.powerCode")+"' ";
    	if(paramMap.get("id")!=null){
    		sql+=" AND id!="+Integer.parseInt(paramMap.get("id").toString());
    	}
    	Long count=Db.queryLong(sql);
    	return count>0;
    }
}
